package com.voxel.sense.infomsg;

import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.example.com.common.app.BaseActivity;
import com.example.com.common.utils.AppUtils;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.IntentUtils;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.example.com.common.view.dialog.IDialog;
import com.example.com.common.view.dialog.NumbProgressDialog;
import com.voxel.sense.infomsg.interfaces.listener.onDownloadCallback;
import com.voxel.sense.infomsg.module.home.BadgeUtils;
import com.voxel.sense.infomsg.module.home.HomeFrag;
import com.voxel.sense.infomsg.module.publish.PublishFrag;
import com.voxel.sense.infomsg.module.taskfrag.TaskListFragment;
import com.voxel.sense.infomsg.module.user.personal.PersonFragment;
import com.voxel.sense.infomsg.service.UpdateVersionService;
import com.voxel.sense.infomsg.utils.InstallUtils;
import com.voxel.sense.infomsg.view.BottomNavigationViewEx;
import com.voxel.sense.infomsg.view.NavHelper;
import com.voxel.sense.infomsg.widget.AppVersionManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.net.RspCode;
import cyy.example.com.facotry.share.SPEngine;

public class MainActivity extends BaseActivity implements
        BottomNavigationView.OnNavigationItemSelectedListener, NavHelper.OnTabChangedListener<Integer> {

    @BindView(R.id.rl_group)
    ConstraintLayout rl_group;
    @BindView(R.id.fg_container)
    FrameLayout fg_container;
    @BindView(R.id.bottm_navigation)
    BottomNavigationViewEx bottm_navigation; //底部导航

    private BadgeView home_badge;//小红点
    private NavHelper<Integer> mNavHelper;
    private ServiceConnection mServiceConnection;
    private UpdateVersionService mService;
    private NumbProgressDialog mAPPUpDialog;
    private Dialog mMessageDialog; //取消弹窗

    private boolean mIsBindService = false;
    private boolean mIsUploadComplete;
    private boolean isRestoreSate = false;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }


    public static void show(Context context) {
        context.startActivity(new Intent(context, MainActivity.class));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            isRestoreSate = true;
        }
        checkVersion();
        super.onCreate(savedInstanceState);
        initNotification();


        EventBus.getDefault().register(this);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        //若异常销毁时，执行恢复工作，fragment可能重叠。需要恢复原来选项
        mNavHelper.performClickMenu(bottm_navigation.getSelectedItemId());
    }

    @Override
    protected void onResume() {
        super.onResume();
        //查看底部是否有红点显示
        if (bottm_navigation.getCurrentItem() == 2) {
            dismissMsgBage();
        } else {
            showNewBadge();
        }
        //是否有更新的版本

        boolean forceUp = SPEngine.getSPEngine().isForceUp();
        //有更新，切实强制更新
        if (AppVersionManager.haveNewVersion() && forceUp) {
            //TODO: 河源版本 暂时隐藏检查更新
            upAppVersion();
        }
    }

    /**
     * 是否有新的消息显示
     */
    private void showNewBadge() {
        if (bottm_navigation.getCurrentItem() == 2) {
            dismissMsgBage();
        } else if (home_badge != null) {
            SPEngine.UserInfo userInfo = SPEngine.getSPEngine().getUserInfo();
            int newMsg = userInfo.getNewMsg();
            home_badge.setVisibility(newMsg > 0 ? View.VISIBLE : View.GONE);
            String count = "";
            if (newMsg >= 100) {
                count = "99+";
                home_badge.setTextSize(9);
            } else {
                home_badge.setTextSize(10);
                count = newMsg + "";
            }
            home_badge.setBadgeCount(count);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {
        super.initData();
        // 从底部导中接管我们的Menu，然后进行手动的触发第一次点击
        Menu menu = bottm_navigation.getMenu();
        //关闭底部导航缩放动画
        bottm_navigation.enableAnimation(false);
        bottm_navigation.enableShiftingMode(false);
        bottm_navigation.enableItemShiftingMode(false);

        //首次初始化选中首页
        if (!isRestoreSate)
            menu.performIdentifierAction(R.id.action_home, 0);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        // 初始化底部辅助工具类
        mNavHelper = new NavHelper<>(this, R.id.fg_container, getSupportFragmentManager(), this);
        if (!isRestoreSate) {
            //添加导航控制的数据界面
            mNavHelper.add(R.id.action_home, new NavHelper.Tab<>(HomeFrag.class, R.string.title_home))
//                .add(R.id.action_discover, new NavHelper.Tab<>(DiscoverFrag.class, R.string.action_discover))
                    .add(R.id.action_publish, new NavHelper.Tab<>(TaskListFragment.class, R.string.home_bm_task))
                    .add(R.id.action_message, new NavHelper.Tab<>(PublishFrag.class, R.string.action_publish))
//                    .add(R.id.action_message, new NavHelper.Tab<>(MessageFrag.class, R.string.action_message))
                    .add(R.id.action_person, new NavHelper.Tab<>(PersonFragment.class, R.string.action_person));
        } else {
            //activity异常情况下销毁重新创建时会保存恢复之前的fragment，这时无需再新建，避免界面重叠
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment frag : fragments) {
                if (frag instanceof HomeFrag) {
                    mNavHelper.add(R.id.action_home, new NavHelper.Tab<>(HomeFrag.class, R.string.title_home, frag));
                } else if (frag instanceof TaskListFragment) {
//                    mNavHelper.add(R.id.action_publish, new NavHelper.Tab<>(PublishFrag.class, R.string.action_publish, frag));
                    mNavHelper.add(R.id.action_publish, new NavHelper.Tab<>(TaskListFragment.class, R.string.home_bm_task, frag));
                } else if (frag instanceof PublishFrag) {
                   mNavHelper.add(R.id.action_message, new NavHelper.Tab<>(PublishFrag.class, R.string.action_message, frag));
//                    mNavHelper.add(R.id.action_message, new NavHelper.Tab<>(MessageFrag.class, R.string.action_message, frag));
                } else if (frag instanceof PersonFragment) {
                    mNavHelper.add(R.id.action_person, new NavHelper.Tab<>(PersonFragment.class, R.string.action_person, frag));
                }
            }

            if (fragments.size() < 4) {
                //恢复的数据中没有包含全部的fragment，创建缺失的fragment
                if (mNavHelper.getTab(R.id.action_home) == null) {
                    mNavHelper.add(R.id.action_home, new NavHelper.Tab<>(HomeFrag.class, R.string.title_home));
                }
                if (mNavHelper.getTab(R.id.action_publish) == null) {
//                    mNavHelper.add(R.id.action_publish, new NavHelper.Tab<>(PublishFrag.class, R.string.action_publish));
                    mNavHelper.add(R.id.action_publish, new NavHelper.Tab<>(TaskListFragment.class, R.string.home_bm_task));
                }
                if (mNavHelper.getTab(R.id.action_message) == null) {
                    mNavHelper.add(R.id.action_message, new NavHelper.Tab<>(PublishFrag.class, R.string.action_message));
                }
                if (mNavHelper.getTab(R.id.action_person) == null) {
                    mNavHelper.add(R.id.action_person, new NavHelper.Tab<>(PersonFragment.class, R.string.action_person));
                }
            }
//
        }
        bottm_navigation.setOnNavigationItemSelectedListener(this);
    }

    @Override
    protected void initEven() {
        super.initEven();
        bottm_navigation.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //移除监听，不然会一直不断的回调监听，导致界面无法显示
                bottm_navigation.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                home_badge = addBadgeViewAt(2, "99+", BadgeView.SHAPE_CIRCLE);
                showNewBadge();
            }
        });
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // 转接事件流到工具类中
        return mNavHelper.performClickMenu(item.getItemId());
    }

    @Override
    public void onTabChanged(NavHelper.Tab<Integer> newTab, NavHelper.Tab<Integer> oldTab) {
        if (R.string.action_message == newTab.extra) {
            dismissMsgBage();
        }
    }


    //添加消息红点

    /**
     * @param position 底部导航item的位置
     * @param text     点内文本
     * @param shape    红点的形状
     * @return
     */
    private BadgeView addBadgeViewAt(int position, String text, int shape) {
        // get position
        ImageView icon = bottm_navigation.getIconAt(position);
        int[] pos = new int[2];
        icon.getLocationInWindow(pos);
        // action bar height
        ActionBar actionBar = getSupportActionBar();
        int actionBarHeight = 0;
        if (null != actionBar) {
            actionBarHeight = actionBar.getHeight();
        }
        int x = (int) (pos[0] + icon.getMeasuredWidth() * 0.7f);
        int y = (int) (pos[1] - actionBarHeight - icon.getMeasuredHeight() * 1.0f);
        // calculate width
        int width = 9 * (text.length() - 1);
        int height = width;

        BadgeView badgeView = BadgeFactory.create(this)
                .setTextColor(Color.WHITE)
                .setWidthAndHeight(width, height)
                .setBadgeBackground(Color.RED)
                .setTextSize(9)
                .setBadgeGravity(Gravity.LEFT | Gravity.TOP)
                .setBadgeCount("")
                .setShape(shape)
                .bind(rl_group);
        badgeView.setX(x);
        badgeView.setY(y);
        return badgeView;
    }


    private long firstTime = 0;

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            super.onBackPressed();
            return;
        }
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            ToastUtil.showToastShort(this, "再按一次退出");
            firstTime = secondTime;
        } else {
            //关闭程序
            AppUtils.hideApp(this, true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventThread(EventEntity entity) {
        if (entity.key.equals(EventBusConstants.PUSH_MSG) || entity.key.equals(EventBusConstants.PUSH_CHECK_TASK_MSG)) {
            //推送消息通知
            if (home_badge == null) {
                return;
            }

            showNewBadge();
        } else if (entity.key.equals(EventBusConstants.SHOW_VERSION_UP_WINDOW)) {
            //收到更新app的通知
            upAppVersion();
        } else if (RspCode.ERROR_ACCOUNT_TOKEN.equals(entity.key)) {
            //收到退出登录的通知
            App.getInstance().logout(1);
        }else if(EventBusConstants.HOME_BADGE_COUNT.equals(entity.key)){
            mBadgeCount = (int) entity.value;
            mBadgeHandler.postDelayed(runnable, 1500);
        }
    }


    /**
     * 版本更新 VersionUpPrompt
     */
    private void upAppVersion() {
        if (mService != null && mService.isUpdata()) {
            //已在下载中，直接显示弹窗
            mAPPUpDialog.show();
        } else {
            boolean forceUp = SPEngine.getSPEngine().isForceUp();
            if (forceUp) {
                showUpdialog(forceUp, "", "版本有重大的升级，请升级更新后再使用app。敬请见谅！");
            } else {
                showUpdialog(forceUp, "", "是否需要更新");
            }
        }
    }

    private void showUpdialog(final boolean isCancel, String title, String text) {
        String cancleStr = isCancel ? "退出程序" : "取消";
        Dialog dialog = DialogImpl.getInstance().showChooseDialog(this, title, text, cancleStr, "确认", new DialogCallBack() {
            @Override
            public void onClick(int what) {
                if (what == DialogImpl.YES) {
                    bindService();
                } else if (isCancel) {
                    finish();
                }
            }
        });
        //若是强制更新，窗口不能取消
        dialog.setCanceledOnTouchOutside(!isCancel);
        dialog.setCancelable(!isCancel);
    }

    /**
     * 绑定app更新服务
     */
    private void bindService() {
        if (mServiceConnection == null) {
            mServiceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                    mIsBindService = true;
                    UpdateVersionService.DownloadBinder downloadBinder = (UpdateVersionService.DownloadBinder) iBinder;
                    mService = downloadBinder.getService();
                    downApp();
                }

                @Override
                public void onServiceDisconnected(ComponentName componentName) {
                    //TODO:服务断开连接后，进行终端下载相关的操作，避免内存泄漏
                    mService.cancelDown();
                    mIsBindService = false;
                    mService = null;
                    mAPPUpDialog = null;
                    mServiceConnection = null;
                }
            };
            //若绑定多次，再进行接触绑定时，会报错
            bindService(new Intent(this, UpdateVersionService.class), mServiceConnection, Service.BIND_AUTO_CREATE);
        } else {
            downApp();
        }
    }

    /**
     * 下载app
     */
    private void downApp() {
        if (mService == null) {
            return;
        }
        if (mAPPUpDialog != null && !mAPPUpDialog.isShowing()) {
            mAPPUpDialog.show();
        }
        mService.downApk(SPEngine.getSPEngine().getAppUrl(), new onDownloadCallback() {
            @Override
            public void onPrepare() {
                if (mAPPUpDialog == null) {
                    mAPPUpDialog = (NumbProgressDialog) DialogImpl.getInstance().shownNumberProgressDialog(MainActivity.this, "正在更新", 1000);
                    boolean forceUp = SPEngine.getSPEngine().isForceUp();
                    if (forceUp) {
                        mAPPUpDialog.setCancelable(false);
                        mAPPUpDialog.setCanceledOnTouchOutside(false);
                    }
                    CancelDownLoadListener();
                }
                mIsUploadComplete = false;
            }

            @Override
            public void onProgress(int progress) {
                if (mAPPUpDialog != null) {
                    mAPPUpDialog.setCurrentProgress(progress);
                }
            }

            @Override
            public void onComplete(File file) {
                dismissDialog();
                upAppVersion();
                unBindUpAppService();
                mIsUploadComplete = true;
                if (FileUtils.isFileExists(file)) {
                    //跳转安装app的意图
//                    startActivity(IntentUtils.getInstallAppIntent(file, Factory.app().getPackageName() + ".android7.fileprovider"));
                    InstallUtils.openFile(App.getInstance().getApplicationContext(), file);
//                    IntentUtils.openAPK(file, App.getInstance().getApplicationContext());
                }
            }

            @Override
            public void onFail(String msg) {
                dismissDialog();
                unBindUpAppService();
                upAppVersion();
                mIsUploadComplete = true;
                ToastUtil.showToastLong(MainActivity.this
                        , msg);

            }

            private void dismissDialog() {
                if (mAPPUpDialog != null) {
                    mAPPUpDialog.dismiss();
                    mAPPUpDialog = null;
                }
            }
        });
    }


    /**
     * 取消下载事件
     */
    private void CancelDownLoadListener() {
        mAPPUpDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(final DialogInterface dialogInterface) {
                //当窗口消失时，需要判断上传是否完全结束
                //1.完成结束了，那么无需任何处理
                //2.没有结束，则需要弹出一个警告，告诉用户是否需要停止上传
                if (mIsUploadComplete) {
                    return;
                }
                if (mMessageDialog == null && !isFinishing()) {
                    mMessageDialog = DialogImpl.getInstance().showChooseDialog(
                            MainActivity.this, "", "下载", "确定", "继续上传", new DialogCallBack() {
                                @Override
                                public void onClick(int what) {
                                    if (what == IDialog.CANCEL && mService != null) {
                                        //停止下载，解除服务绑定
                                        unBindUpAppService();
                                    } else {
                                        //继续下载
                                        if (mAPPUpDialog != null && !isFinishing()) {
                                            mAPPUpDialog.show();
                                        }
                                        mMessageDialog.dismiss();
                                    }
                                }
                            });
                    mMessageDialog.setCancelable(false);
                    mMessageDialog.setCanceledOnTouchOutside(false);
                } else if (!isFinishing()) {
                    mMessageDialog.show();
                }
            }
        });
    }

    private void checkVersion() {
        if (NetworkUtils.isConnected()) {
            AppVersionManager.checkVerson(true);
        }
    }

    /**
     * 解除服务绑定
     */
    private void unBindUpAppService() {
        if (mServiceConnection != null && mIsBindService) {
            unbindService(mServiceConnection);
            mIsBindService = false;
            mServiceConnection = null;
            mService = null;
            mAPPUpDialog = null;
        }
    }

    /**
     * 隐藏消息模块红点
     */
    private void dismissMsgBage() {
        if (home_badge == null) return;
        home_badge.setVisibility(View.GONE);
        SPEngine.getSPEngine().getUserInfo().setNewMsg(0);
    }
    private MainActivity mSelfActivity = MainActivity.this;
    private Handler mBadgeHandler = new Handler();
    private int mBadgeCount;
    private static final String CHANNEL_ID = "heliquan";
    private static final long[] VIBRATION_PATTERN = new long[]{0, 180, 80, 120};
    private NotificationManager notificationManager;
    private String packageName;
    Runnable runnable = new Runnable(){
        @Override
        public void run(){
            if(Build.MANUFACTURER.equalsIgnoreCase("xiaomi")){
                PackageManager pm = getPackageManager();
                Intent launchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        mSelfActivity, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(mSelfActivity, CHANNEL_ID)
                        .setSmallIcon(getApplicationInfo().icon)
                        .setContentTitle(pm.getApplicationLabel(getApplicationInfo()).toString())
                        .setTicker("Ticker:" + mBadgeCount)
                        .setContentText("环保管家" + mBadgeCount + "个")
                        .setWhen(System.currentTimeMillis())
                        .setAutoCancel(true)
                        .setContentIntent(pendingIntent);
                Notification notification = builder.build();
                BadgeUtils.getBadgeOfMINU(notification, mBadgeCount);
                notificationManager.notify(0, notification);
            }
            else{
                BadgeUtils.setBadgeCount(mSelfActivity, mBadgeCount);
            }
            												mBadgeHandler.postDelayed(this, 1500);
        }
    };

    private void initNotification(){
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT >= 26){
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "test for He.", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setVibrationPattern(VIBRATION_PATTERN);
            notificationManager.createNotificationChannel(channel);
        }
        packageName = getApplicationInfo().packageName;
    }
}
